package com.kira.solo.schedule.list

import com.alipay.hulu.shared.io.bean.RecordCaseInfo
import com.alipay.hulu.shared.io.db.GreenDaoManager
import com.alipay.hulu.shared.io.db.RecordCaseInfoDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 获取用例
 * @packageName com.kira.solo.schedule.list
 * @date 2024/1/24 14:36
 * @author zhanglei
 */
@Singleton
class FullCaseRepo @Inject constructor() {
    private val dataFlow = MutableStateFlow(emptyList<RecordCaseInfo>())

    /**
     * 查询用例
     */
    suspend fun queryCase(count: Int = 20): List<RecordCaseInfo> {
        return withContext(Dispatchers.IO) {
            val list = try {
                GreenDaoManager.getInstance().recordCaseInfoDao.queryBuilder()
                    .orderDesc(RecordCaseInfoDao.Properties.GmtCreate)
                    .limit(count)
                    .build()
                    .list() ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
            dataFlow.updateAndGet { list }
        }
    }

    operator fun get(id: Long): RecordCaseInfo? {
        return dataFlow.value.firstOrNull { it.id == id }
    }

    suspend fun query(id: Long): RecordCaseInfo? {
        return queryCase().firstOrNull { it.id == id }
    }
}